﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;
using System.ComponentModel;
using Yitter.IdGenerator;
using static QRCoder.Base64QRCode;

namespace Admin.NET.Plugin.ApprovalFlow.Service;

/// <summary>
/// 审批流程服务
/// </summary>
[ApiDescriptionSettings(ApprovalFlowConst.GroupName, Order = 100)]
public class ApprovalFlowService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<ApprovalFlow> _approvalFlowRep;
    private readonly UserManager _userManager;
    public ApprovalFlowService(SqlSugarRepository<ApprovalFlow> approvalFlowRep, UserManager userManager)
    {
        _approvalFlowRep = approvalFlowRep;
        _userManager = userManager;
    }

    /// <summary>
    /// 分页查询审批流
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]
    public async Task<SqlSugarPagedList<ApprovalFlowOutput>> Page(ApprovalFlowInput input)
    {
    return await _approvalFlowRep.AsQueryable()
    .WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey), u => u.Code.Contains(input.SearchKey.Trim()) || u.Name.Contains(input.SearchKey.Trim()) || u.Remark.Contains(input.SearchKey.Trim()))
    .WhereIF(!string.IsNullOrWhiteSpace(input.Code), u => u.Code.Contains(input.Code.Trim()))
    .WhereIF(!string.IsNullOrWhiteSpace(input.Name), u => u.Name.Contains(input.Name.Trim()))
    .WhereIF(!string.IsNullOrWhiteSpace(input.Remark), u => u.Remark.Contains(input.Remark.Trim()))
    .Select<ApprovalFlowOutput>()
    .ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加审批流
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddApprovalFlowInput input)
    {
        var entity = input.Adapt<ApprovalFlow>();
        entity.Id = YitIdHelper.NextId();
        if (input.Code == null)
        {
            entity.Code = await LastCode("");
        }
        //string flowjson = $"{{\"tableId\": {entity.Id},//审批id\"workFlowDef\": {{\"name\": \"{entity.Name}\",//审批名称}},\"directorMaxLevel\": 4,//审批主管最大层级\"flowPermission\": [],//发起人\"nodeConfig\": {{\"nodeName\": \"发起人\",//节点名称\"type\": 0,// 0 发起人 1审批 2抄送 3条件 4路由\"priorityLevel\": \"\",// 条件优先级\"settype\": \"\",// 审批人设置 1指定成员 2主管 4发起人自选 5发起人自己 7连续多级主管\"selectMode\": \"\", //审批人数 1选一个人 2选多个人\"selectRange\": \"\", //选择范围 1.全公司 2指定成员 2指定角色\"directorLevel\": \"\", //审批终点  最高层主管数\"examineMode\": \"\", //多人审批时采用的审批方式 1依次审批 2会签\"noHanderAction\": \"\",//审批人为空时 1自动审批通过/不允许发起 2转交给审核管理员\"examineEndDirectorLevel\": \"\", //审批终点 第n层主管\"ccSelfSelectFlag\": \"\", //允许发起人自选抄送人\"conditionList\": [], //当审批单同时满足以下条件时进入此流程\"nodeUserList\": [], //操作人\"childNode\": {{}}, \"nodeUserList\": []}},\"conditionNodes\": []}}";

        string flowjson = $"{{\"tableId\": {entity.Id},\"workFlowDef\": {{\"name\": \"{entity.Name}\"}},\"directorMaxLevel\": 4,\"flowPermission\": [],\"nodeConfig\": {{\"nodeName\": \"发起人\",\"type\": 0,\"priorityLevel\": \"\",\"settype\": \"\",\"selectMode\": \"\", \"selectRange\": \"\",\"directorLevel\": \"\", \"examineMode\": \"\", \"noHanderAction\": \"\",\"examineEndDirectorLevel\": \"\", \"ccSelfSelectFlag\": \"\", \"conditionList\": [], \"nodeUserList\": [], \"childNode\": {{}}, \"nodeUserList\": []}},\"conditionNodes\": []}}";
        //string strflow = string.Format($"{""tableId"":{0},""workFlowDef"":{""name"":""{1}""},""directorMaxLevel"":4,""flowPermission"":[],""nodeConfig"":{""nodeName"":""发起人"",""type"":0,""priorityLevel"":"""",""settype"":"""",""selectMode"":"""",""selectRange"":"""",""directorLevel"":"""",""examineMode"":"""",""noHanderAction"":"""",""examineEndDirectorLevel"":"""",""ccSelfSelectFlag"":"""",""conditionList"":[],""nodeUserList"":[],""childNode"":{}},""conditionNodes"":[]}",entity.Id,entity.Name);
        entity.FlowJson = flowjson;
        await _approvalFlowRep.InsertAsync(entity);
        return entity.Id;
    }

    /// <summary>
    /// 更新审批流
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateApprovalFlowInput input)
    {
        var entity = input.Adapt<ApprovalFlow>();
        await _approvalFlowRep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除审批流
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteApprovalFlowInput input)
    {
        var entity = await _approvalFlowRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _approvalFlowRep.FakeDeleteAsync(entity);  // 假删除
    }

    /// <summary>
    /// 获取审批流
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<ApprovalFlow> GetDetail([FromQuery] QueryByIdApprovalFlowInput input)
    {
        return await _approvalFlowRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 根据编码获取审批流信息
    /// </summary>
    /// <param name="code"></param>
    /// <returns></returns>
    public async Task<ApprovalFlow> GetInfo([FromQuery] string code)
    {
        return await _approvalFlowRep.GetFirstAsync(u => u.Code == code);
    }

    /// <summary>
    /// 获取审批流列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<List<ApprovalFlowOutput>> GetList([FromQuery] ApprovalFlowInput input)
    {
        return await _approvalFlowRep.AsQueryable().Select<ApprovalFlowOutput>().ToListAsync();
    }

    /// <summary>
    /// 获取今天创建的最大编号
    /// </summary>
    /// <param name="prefix"></param>
    /// <returns></returns>
    private async Task<string> LastCode(string prefix)
    {
        var today = DateTime.Now.Date;
        var count = await _approvalFlowRep.AsQueryable().Where(u => u.CreateTime >= today).CountAsync();
        return prefix + DateTime.Now.ToString("yyMMdd") + string.Format("{0:d2}", count + 1);
    }

    /// <summary>
    /// 匹配审批流程
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    [NonAction]
    public async Task MatchApproval(HttpContext context)
    {
        var request = context.Request;
        var response = context.Response;

        var path = request.Path.ToString().Split("/");

        var method = request.Method;
        var qs = request.QueryString;
        var h = request.Headers;
        var b = request.Body;

        var requestHeaders = request.Headers;
        var responseHeaders = response.Headers;

        await Task.CompletedTask;
    }

    ///// <summary>
    ///// 上传头像 🔖
    ///// </summary>
    ///// <param name="file"></param>
    ///// <returns></returns>
    //[ApiDescriptionSettings(Name = "UploadShare"), HttpPost]
    //public async Task<SysFile> UploadFormFile([Required] IFormFile file)
    //{
    //    var sysFile = await UploadFile(new UploadFileInput { File = file, AllowSuffix = _imageType, SavePath = "upload/avatar" });

    //    var sysUserRep = _sysFileRep.ChangeRepository<SqlSugarRepository<SysUser>>();
    //    var user = await sysUserRep.GetByIdAsync(_userManager.UserId);
    //    // 删除已有头像文件
    //    if (!string.IsNullOrWhiteSpace(user.Avatar))
    //    {
    //        var fileId = Path.GetFileNameWithoutExtension(user.Avatar);
    //        await DeleteFile(new DeleteFileInput { Id = long.Parse(fileId) });
    //    }
    //    await sysUserRep.UpdateAsync(u => new SysUser() { Avatar = sysFile.Url }, u => u.Id == user.Id);
    //    return sysFile;
    //}

    /// <summary>
    /// 用户提交审批文件
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "UploadFormFile"), HttpPost]
    public async Task<SysFile> UploadFormFile([Required] IFormFile file)
    {
        if (_userManager.IsNullOrEmpty())
        {
            throw Oops.Oh("登录失效，请重新登录");
        }
        var service = App.GetRequiredService<SysFileService>();
        UploadFileInput input = new UploadFileInput();
        input.File = file;
        input.AllowSuffix = ".gif,.jpg,.png,.bmp,.zip,.rar,.jepg,.xls,.xlsx,.doc,.docx,.pdf,.ppt,.pptx,.7z";
        input.SavePath = $"upload/{_userManager.TenantId}/ApprovalFlow";
        
        return await service.UploadFile(input );
    }
    /// <summary>
    /// 用户提交审批文件
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "DeleteFormFile"), HttpPost]
    [DisplayName("删除文件")]
    public async Task DeleteFormFile([Required] DeleteFileInput input)
    {
        if (_userManager.IsNullOrEmpty())
        {
            throw Oops.Oh("登录失效，请重新登录");
        }
        var service = App.GetRequiredService<SysFileService>();
          
        await service.DeleteFile(input);
    }
}